#pragma once

#include <iostream>
#include "Socket.hpp"
#include <string>
#include <memory>
#include <functional>
#include <jsoncpp/json/json.h>
#include "InetAddr.hpp"

using namespace SocketModule;

// client->server
class Request
{
public:
    Request()
    {
    }

    Request(int x, int y, char oper)
        : _x(x), _y(y), _oper(oper)
    {
    }

    std::string Serialize()
    {
        Json::Value root;
        root["x"] = _x;
        root["y"] = _y;
        root["oper"] = _oper;

        Json::FastWriter writer;
        std::string s = writer.write(root);
        return s;
    }

    bool Deserialize(std::string &in)
    {
        Json::Value root;
        Json::Reader reader;
        bool ok = reader.parse(in, root);
        if (ok)
        {
            _x = root["x"].asInt();
            _y = root["y"].asInt();
            _oper = root["oper"].asInt(); // ascll码值
        }
        return ok;
    }

    ~Request() {}
    int X() { return _x; }
    int Y() { return _y; }
    char Oper() { return _oper; }

private:
    int _x;
    int _y;
    char _oper;
};

// server->client
class Response
{
public:
    Response() {}
    Response(int result, int code) : _result(result), _code(code)
    {
    }

    std::string Serialize()
    {
        Json::Value root;
        root["result"] = _result;
        root["code"] = _code;
        Json::FastWriter writer;
        return writer.write(root);
    }

    bool Deserialize(std::string &in)
    {
        Json::Value root;
        Json::Reader reader;
        bool ok = reader.parse(in, root);
        if (ok)
        {
            _result = root["result"].asInt();
            _code = root["code"].asInt();
        }
        return ok;
    }

    ~Response() {}
    void SetResult(int res)
    {
        _result = res;
    }

    void SetCode(int code)
    {
        _code = code;
    }

    void ShowResult()
    {
        std::cout << "计算的结果是：" << _result << "[" << _code << "]" << std::endl;
    }

private:
    int _result;
    int _code; // 0代表success，其他值表示不同的错误
};

const std::string sep = "\r\n";
using func_t = std::function<Response(Request &req)>;

class Protocol
{
public:

    Protocol(){}
    Protocol(func_t func) : _func(func)
    {
    }

    // 封装报头
    std::string Encode(const std::string &jsonstr)
    {
        // 50\r\n{"x":10,"y":20,"oper":'+}\r\n
        std::string len = std::to_string(jsonstr.size());
        return len + sep + jsonstr + sep;
    }

    // 判断报文完整性
    bool Decode(std::string &buffer, std::string *package)
    {
        ssize_t pos = buffer.find(sep);
        if (pos == std::string::npos)
            return false;

        std::string package_len_str = buffer.substr(0, pos);
        int package_len_int = std::stoi(package_len_str);

        int target_len = package_len_str.size() + package_len_int + 2 * sep.size();
        if (buffer.size() < target_len)
            return false;

        // buffer里面一定有一个及以上的报文
        *package = buffer.substr(pos + sep.size(), package_len_int);
        buffer.erase(0, target_len);
        return true;
    }

    void GetRequest(std::shared_ptr<Socket> &sock, InetAddr &client)
    {
        std::string buffer_queue;
        while (true)
        {
            int n = sock->Recv(&buffer_queue);
            if (n > 0)
            {
                std::string json_package;
                // 1.解析报文，提取完整的josn请求，如果不完整，就让服务器继续读取数据
                while (Decode(buffer_queue, &json_package))
                {
                    // 这里一定拿到了一个完整的报文，接下来就是反序列化
                    LOG(LogLevel::DEBUG)<<client.StringAddr()<<"请求："<<json_package;
                    Request req;
                    bool ok = req.Deserialize(json_package);
                    if (!ok)
                        continue;

                    // 这里我们一定得到一个内部属性已经被设置的req了
                    // req->response,就是要完成计算任务，业务处理！！！！！
                    Response resp = _func(req);

                    // 序列化
                    std::string json_str = resp.Serialize();
                    // 添加报头
                    std::string send_str = Encode(json_str);

                    // 直接发送
                    sock->Send(send_str);
                }
            }
            else if (n == 0)
            {
                LOG(LogLevel::INFO) << "client: " << client.StringAddr() << "Quit";
                break;
            }
            else
            {
                LOG(LogLevel::WARNING) << "client: " << client.StringAddr() << ",recv,error";
                break;
            }
        }
    }

    bool GetResponse(std::shared_ptr<Socket>&client,std::string &resp_buffer,Response* resp)
    {
        int n = client->Recv(&resp_buffer);
        if(n>0)
        {
            std::string json_package;
            while(Decode(resp_buffer,&json_package))
            {
                //走到这里可以确认我们已经拿到了一个完整的报文
                resp->Deserialize(json_package);
            }
            return true;
        }
        else if(n==0)
        {
            std::cout<<"server quit"<<std::endl;
            return false;
        }
        else
        {
            std::cout<<"recv error"<<std::endl;
            return false;
        }
    }

    std::string BuildRequestString(int x,int y,char oper)
    {
        //1.构建一个完整的请求
        Request req(x,y,oper);
        //2.序列化
        std::string json_req = req.Serialize();

        //3.添加报头
        return Encode(json_req);
    }

    ~Protocol() {}

private:
    func_t _func;
};
